import Vue from 'vue';
import store from '../store';
import VueRouter from 'vue-router';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import { MessageBox } from 'element-ui'
import { PrevLoading } from '@/utils/loading.js';
import { AuthStorage } from "@/utils/AuthStorage";
import Util from "@/utils/Util"

// 解决 `element ui` 导航栏重复点菜单报错问题
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
	return originalPush.call(this, location).catch((err) => err);
};

// 安装 VueRouter 插件
Vue.use(VueRouter);

// 定义动态路由
const dynamicRoutes = [
	{
		path: '/',
		name: 'index',
		component: 'layout/index',
		redirect: '/home',
		meta: {
			title: '首页',
			auth: [],
			icon: "el-icon-search"
		},
		children: [
			{
				path: '/bl/search',
				name: 'SearchManage',
				component: () => import('@/views/bl/SearchManage'),
				meta: {
					title: '统计查询',
					isHide: true,
					isAffix: true,
					isKeepAlive: true,
					icon: 'el-icon-search',
				},
			},{
				path: '/config',
				name: 'ExcelTemplateManage',
				component: () => import('@/views/bl/ExcelTemplateManage'),
				meta: {
					title: '设置中心',
					icon: 'iconfont icon-setting',
					isHide: true,
					isKeepAlive: true
				},
			},{
				path: '/log',
				name: 'Log',
				component: () => import('@/views/system/log/Log'),
				meta: {
					title: '系统日志',
					icon: 'iconfont icon-method-setting',
					isHide: true,
					isKeepAlive: true
				},
			},{
				path: '/me',
				name: 'UserInfo',
				component: () => import('@/views/system/user/UserInfo'),
				meta: {
					title: '个人信息',
					icon: 'el-icon-user',
					isHide: true,
					isKeepAlive: true
				},
			},{
				path: '/home',
				name: 'home',
				component: () => import('@/views/home/home'),
				meta: {
					title: '首页',
					icon: 'el-icon-user',
					isHide: true,
					isKeepAlive: true
				},
			}
		],
	},
	{
		path: '/report',
		name: 'index',
		component: 'layout/index',
		redirect: '/bl/report',
		meta: {
			title: '报告生成',
			auth: [],
			icon: "el-icon-document"
		},
		children: [
			{
				path: '/bl/report',
				name: 'DocxReportManage',
				component: () => import('@/views/bl/DocxReportManage'),
				meta: {
					title: '报告生成',
					isHide: true,
					isAffix: true,
					isKeepAlive: true,
					icon: 'el-icon-document',
				},
			}
		]
	}
];

// 定义静态路由
const staticRoutes = [
	{
		path: '/login',
		name: 'login',
		component: () => import('@/views/login'),
		meta: {
			title: '登录',
		},
	},{
		path: '/404',
		name: 'notFound',
		component: () => import('@/views/error/404.vue'),
		meta: {
			title: 'message.staticRoutes.notFound',
		},
	},
	{
		path: '/401',
		name: 'noPower',
		component: () => import('@/views/error/401.vue'),
		meta: {
			title: 'message.staticRoutes.noPower',
		},
	},
];

// 管理员理由
const adminRoute = {
	path: '/system',
	name: 'system',
	component: 'layout/index',
	meta: {
		title: '组织结构',
		isLink: false,
		isHide: false,
		isKeepAlive: true,
		isAffix: false,
		isIframe: false,
		icon: "iconfont icon-tongxunlu"
	},
	children: [
		{
			path: '/admin/group',
			name: 'GroupTable',
			component: () => import('@/views/system/group/GroupTable'),
			meta: {
				title: '组织管理',
				isKeepAlive: true,
				icon: 'iconfont icon-org-home'
			},
		},{
			path: '/admin/role',
			name: 'GroupRole',
			component: () => import('@/views/system/role/GroupRole'),
			meta: {
				title: '角色管理',
				isKeepAlive: true,
				icon: 'iconfont icon-user-authority'
			},
		},{
			path: '/admin/user',
			name: 'GroupUser',
			component: () => import('@/views/system/user/GroupUser'),
			meta: {
				title: '用户管理',
				isKeepAlive: true,
				icon: 'iconfont icon-user-edit'
			},
		}
	]
}

// 加载静态路由
const createRouter = () =>
	new VueRouter({
		routes: staticRoutes,
	});

// 创建路由
const router = createRouter();

// 加载 loading
PrevLoading.start();

// 多级嵌套数组处理成一维数组
export function formatFlatteningRoutes(arr) {
	if (!arr || arr.length <= 0) return [];
	for (let i = 0; i < arr.length; i++) {
		if (arr[i].children) {
			arr = arr.slice(0, i + 1).concat(arr[i].children, arr.slice(i + 1));
		}
	}
	return arr;
}

// 处理 tagsViewList 数据，默认路由全部缓存
// isKeepAlive 处理 `name` 值，进行路由缓存
export function formatTwoStageRoutes(arr) {
	if (!arr || arr.length <= 0) return [];
	const newArr = [];
	const cacheList = [];
	arr.forEach((v) => {
		newArr.push({ ...v });
		cacheList.push(v.name);
		store.dispatch('keepAliveNames/setCacheKeepAlive', cacheList);
	});
	return newArr;
}

// 缓存多级嵌套数组处理后的一维数组(tagsView、菜单搜索中使用：未过滤隐藏的(isHide))
export function setCacheTagsViewRoutes(arr) {
	// 先处理有权限的路由，否则 tagsView、菜单搜索中无权限的路由也将显示
	// 添加到 vuex setTagsViewRoutes 中
	store.dispatch('tagsViewRoutes/setTagsViewRoutes', formatTwoStageRoutes(formatFlatteningRoutes(arr)));
}

// 递归处理多余的 layout : <router-view>，让需要访问的组件保持在第一层 layout 层。
// 因为 `keep-alive` 只能缓存二级路由
// 默认初始化时就执行
export function keepAliveSplice(to) {
	if (to.matched && to.matched.length > 2) {
		to.matched.map((v, k) => {
			if (v.components.default instanceof Function) {
				v.components.default().then((components) => {
					if (components.default.name === 'parent') {
						to.matched.splice(k, 1);
						router.push({ path: to.path, query: to.query });
						keepAliveSplice(to);
					}
				});
			} else {
				if (v.components.default.name === 'parent') {
					to.matched.splice(k, 1);
					keepAliveSplice(to);
				}
			}
		});
	}
}

// 处理后端返回的 `component` 路径，拼装实现懒加载
export function loadView(component) {
	if (component.indexOf('layout') > -1) {
		return () => Promise.resolve(require(`@/${component}`));
	} else {
		return () => Promise.resolve(require(`@/views/${component}`));
	}
}

// 递归处理每一项 `component` 中的路径
export function dynamicRouter(routes) {
	return routes.map((view) => {
		if (typeof view.component !== 'function') {
			if (view.component) {
				view.component = loadView(view.component)
			}
			if (view.children) {
				dynamicRouter(view.children);
			}
		}
		return view;
	});
}

// 重置路由
export function resetRouter() {
	router.matcher = createRouter().matcher;
}

// 延迟关闭进度条
export function delayNProgressDone(time = 300) {
	setTimeout(() => {
		NProgress.done();
	}, time);
}

/**
 * 获取当前登录用户信息
 */
export function getUserInfo(router, to, next) {
	const userInfo = store.state.userInfos.userInfo
	// 获取用户信息时获取菜单
	if (Util.isEmpty(userInfo)) {
		store.dispatch('userInfos/getUserInfo')
			.then((res) => {
				getSysMenus(router,to, next)
			})
	} else {
		next();
		delayNProgressDone(0);
	}
}

/**
 * 添加路由菜单
 */
export function getSysMenus(router, to, next) {
	resetRouter();
	const userInfo = AuthStorage.getUserInfo();
	if (userInfo.groupAdmin || userInfo.systemAdmin) {
		dynamicRoutes.splice(0, 0, adminRoute)
		dynamicRoutes[1].redirect = '/bl/search'
		dynamicRoutes[1].meta.title = '统计查询'
	} else {
		// 验证是否有报告生成菜单权限
		let reportIndex = -1;
		// 验证是否有统计查询菜单权限
		let queryIndex = -1;
		if (userInfo.roles && userInfo.roles.length > 0) {
			// 验证是否有报告生成菜单权限
			reportIndex = userInfo.roles.findIndex(item => item.roleCode === 'REPORT_MENU')
			// 验证是否有统计查询菜单权限
			queryIndex = userInfo.roles.findIndex(item => item.roleCode === 'QUERY_MENU')
		}
		debugger
		if (reportIndex === -1) {
			dynamicRoutes.splice(1,1)
		}
		if (queryIndex === -1) {
			dynamicRoutes[0].children.splice(0,1)
		} else {
			dynamicRoutes[0].redirect = '/bl/search'
			dynamicRoutes[0].meta.title = '统计查询'
		}
	}
	store.dispatch('routesList/setRoutesList', dynamicRoutes);
	const awaitRoute = dynamicRouter(dynamicRoutes);
	[...awaitRoute, { path: '*', redirect: '/404' }].forEach((route) => {
		router.addRoute({ ...route });
	});
	setCacheTagsViewRoutes(JSON.parse(JSON.stringify(dynamicRoutes)));
	next({ ...to, replace: true });
}

router.beforeEach((to, from, next) => {
	keepAliveSplice(to);
	NProgress.configure({ showSpinner: false });
	let token = AuthStorage.getAccessToken();
	if (to.path === '/login') {
		if (token) {
			next('/');
		} else {
			next();
		}
		delayNProgressDone();
	} else {
		NProgress.start();
		const refresh = AuthStorage.getRefreshToken();
		// 免登陆页面
		if (to.meta && to.meta.ignoreAuth) {
			next();
			delayNProgressDone();
		} else if (!token && !refresh) {
			next('/login');
			AuthStorage.clear();
			delayNProgressDone();
		} else if (!token && refresh) {
			store.dispatch('userInfos/refresh_token')
				.then(res => {
					if (res.code === 401) {
						next('/login');
						AuthStorage.clear();
						delayNProgressDone();
					} else {
						getUserInfo(router, to, next)
					}
				})
		} else {
			getUserInfo(router, to, next)
		}
	}
});

// 路由加载后
router.afterEach(() => {
	PrevLoading.done();
	delayNProgressDone();
});

// 导出路由
export default router;
